package com.sczmgk.hotline_pzh.ui;

import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;

import com.sczmgk.hotline_pzh.R;
import com.sczmgk.hotline_pzh.base.BaseActivity;
import com.sczmgk.hotline_pzh.callback.SimplePaserJsonCallback;
import com.sczmgk.hotline_pzh.callback.VerfyCallback;
import com.sczmgk.hotline_pzh.constants.Constants;
import com.sczmgk.hotline_pzh.db.impl.UserDaoImpl;
import com.sczmgk.hotline_pzh.dialog.DialogFactory;
import com.sczmgk.hotline_pzh.dialog.MessageDialog;
import com.sczmgk.hotline_pzh.entity.BaseEntity;
import com.sczmgk.hotline_pzh.entity.IndicatorInfos;
import com.sczmgk.hotline_pzh.entity.User;
import com.sczmgk.hotline_pzh.httputils.MyHttp;
import com.sczmgk.hotline_pzh.sp.CacheUtils;
import com.sczmgk.hotline_pzh.utils.CommonUtils;
import com.sczmgk.hotline_pzh.utils.MyToast;
import com.sczmgk.hotline_pzh.utils.SecurityCodeUtils;
import com.sczmgk.hotline_pzh.utils.TimerUtils;
import com.sczmgk.hotline_pzh.utils.Tools;
import com.sczmgk.hotline_pzh.utils.UIUtils;
import com.sczmgk.hotline_pzh.view.RegistItemView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/12/5 0005.
 */
public class ChangePhoneActivity extends BaseActivity {

    /*下一步按钮*/
    private Button mBtnNext;

    /*新手机号和获取验证码的条目控件*/
    private RegistItemView mNewPhone;
    private RegistItemView mGetKey;

    /*从数据库拉取的用户信息*/
    private User user;
//    private String inputPwd;

    private TimerUtils timerUtils;
    private MessageDialog errorDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_phone);
        CommonUtils.addActivity(this);
        setHeader();

        initView();

        initData();

        setListener();
    }

    /**
     * 设置头
     */
    private void setHeader() {
        setTitle(R.string.change_new_phone);
        setLeftBtnVisibility(View.VISIBLE);
    }

    /**
     * 初始化控件
     */
    private void initView() {

        //新手机号
        mNewPhone = (RegistItemView) findViewById(R.id.riv_change_phone);

        //获取验证码
        mGetKey = (RegistItemView) findViewById(R.id.riv_change_key);

        //下一步
        mBtnNext = (Button) findViewById(R.id.btn_new_phone_next);
    }

    /**
     * 初始化数据
     */
    private void initData() {

        //根据uid从数据库获取用户信息
        int userid = CacheUtils.getIntData(ChangePhoneActivity.this, Constants.LOGIN_UID, 0);
        user = UserDaoImpl.getIntance(ChangePhoneActivity.this).findByQuery(userid);

        if (!TextUtils.isEmpty(user.phone)) {
            mNewPhone.setText(user.phone);
            mNewPhone.setSelection(user.phone.length());
        }
    }

    /**
     * 设置监听
     */
    private void setListener() {

        //获取验证码的点击事件
        mNewPhone.setOnGetKeyOnclick(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //获取验证码
                final String phone = mNewPhone.getText();
                //判断是否是电话号码
                boolean isPhone = Tools.isMobilePhoneNumber(phone);
                if (isPhone) {
                    //TODO 获取验证码
                    SecurityCodeUtils.getCode(ChangePhoneActivity.this, phone, 1, user.userid, new VerfyCallback() {

                        @Override
                        public void onSuccess() {
                            timerUtils = new TimerUtils();
                            timerUtils.startTimer(ChangePhoneActivity.this, mNewPhone.getVerifyButton());
                            MyToast.show(ChangePhoneActivity.this, "验证码已发送至:" + phone);
                        }

                        @Override
                        public void onError(BaseEntity.MyError mError) {
                            if (errorDialog == null) {
                                errorDialog = DialogFactory.warningDialog(ChangePhoneActivity.this, mError.msg);
                            }else if (!errorDialog.isShowing()){
                                errorDialog = DialogFactory.warningDialog(ChangePhoneActivity.this, mError.msg);
                            }
                        }

                        @Override
                        public void onLoadIndicatorDataCallback(List<IndicatorInfos> indicatorInfos) {

                        }
                    });
                } else {
                    MyToast.show(ChangePhoneActivity.this, "请输入正确的手机号");
                }
            }
        });

        //下一步的点击事件
        mBtnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String phone = mNewPhone.getText();
                String key = mGetKey.getText();

                if (Tools.isEmpty(phone)) {
                    MyToast.show(ChangePhoneActivity.this, "手机号不能为空");
                    return;
                }

                if (Tools.isEmpty(key)) {
                    MyToast.show(ChangePhoneActivity.this, "验证码不能为空");
                    return;
                }

                boolean isPhone = Tools.isMobilePhoneNumber(phone);
                if (isPhone) {
                    //提交数据
                    submitData(phone, key);
                } else {
                    MyToast.show(ChangePhoneActivity.this, "请输入正确的手机号");
                }
            }
        });
    }

    /**
     * 提交数据
     *
     * @param phone 新手机号
     * @param key   验证码
     */
    private void submitData(String phone, String key) {

        //提交用户数据
        submitUserData(phone, key);
    }

    /**
     * 提交用户信息到服务器并更新
     *
     * @param phone 电话号码
     */
    private void submitUserData(final String phone, String key) {

        Map<String, Object> maps = new HashMap<>();
        maps.put("userid", user.userid);
//        maps.put("password", inputPwd);
        maps.put("phone", phone);
        maps.put("verifycodes", key);

        //TODO 更换调用接口
        MyHttp.requestByCommon(Constants.BASE_URL + Constants.POST_UPDATE_PHONE, maps, MyHttp.POST, ChangePhoneActivity.this, false, null, new SimplePaserJsonCallback() {
            @Override
            public void onVerifyIsNull() {

                //提交成功后将地址更新至数据库
                user.phone = phone;
                UserDaoImpl.getIntance(ChangePhoneActivity.this).updata(user);

                //返回地址结果
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
//                        Intent intent = new Intent();
//                        setResult(RESULT_OK, intent);
                        // TODO 电话号码修改后,跳转到登录界面
                        CacheUtils.cacheBooleanData(ChangePhoneActivity.this, Constants.IS_LOGIN_KEY, false);
                        CommonUtils.finishActivity();
                        UIUtils.startActivity(ChangePhoneActivity.this, LoginActivity.class);
                        finish();
                    }
                }, 200);

            }

            @Override
            public void onVerifySuccess(String dataRaw, boolean isCache) {
            }

            @Override
            public void onErrorCodeError(BaseEntity.MyError mError) {
                super.onErrorCodeError(mError);
                DialogFactory.warningDialog(ChangePhoneActivity.this, mError.msg);
            }
        });
    }


    @Override
    public void handleMessage(Message msg) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (timerUtils != null && timerUtils.timerIsRunning()){
            timerUtils.stopTimer(mGetKey.getVerifyButton());
        }
    }

    @Override
    public boolean getIsNeedLogin() {
        return false;
    }
}
